package com.ruoyi.common.repository;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.ruoyi.common.utils.ListUtils;

import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;

public class FieldFiller<SourceBean> {

    private List<SourceBean> list;

    public FieldFiller(List<SourceBean> list) {
        this.list = list;
    }

    public <KeyType, TargetBean, FieldType, Service> List<SourceBean> join(Service service,
                                                                           BiFunction<Service, List<KeyType>, List<TargetBean>> getTargetList,
                                                                           Function<SourceBean, KeyType> sourceForeignKey,
                                                                           Function<TargetBean, KeyType> targetJoinKey,
                                                                           Function<TargetBean, FieldType> getFieldValue,
                                                                           BiConsumer<SourceBean, FieldType> valueSetter) {
        List<KeyType> foreignKeyList = ListUtils.listField(list, sourceForeignKey);
        foreignKeyList = CollectionUtil.distinct(foreignKeyList);
        List<TargetBean> targetBeanList = getTargetList.apply(service, foreignKeyList);
        Map<KeyType, TargetBean> map = new HashMap<>();
        targetBeanList.forEach(targetBean -> map.put(targetJoinKey.apply(targetBean), targetBean));
        list.forEach(sourceBean -> {
            KeyType key = sourceForeignKey.apply(sourceBean);
            if (ObjectUtil.isEmpty(key)) {
                return ;
            }
            TargetBean targetBean = map.get(key);
            if (ObjectUtil.isNotEmpty(targetBean)) {
                FieldType fieldValue = getFieldValue.apply(targetBean);
                valueSetter.accept(sourceBean, fieldValue);
            }
        });
        return list;
    }
}
